package com.mingqijia.gassafety.job.service.screen.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.auth.CompanyMapper;
import com.mingqijia.gassafety.job.request.screen.ScreenCompanyManageReq;
import com.mingqijia.gassafety.job.response.screen.PlatformCompanyManageResp;
import com.mingqijia.gassafety.job.response.screen.QueryCompanyResp;
import com.mingqijia.gassafety.job.service.screen.ScreenStatisticsService;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ScreenStatisticsServiceImpl implements ScreenStatisticsService {

    @Autowired
    private VccAuthoritiesProvider provider;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private DtuMapper dtuMapper;

    @Value(value = "${gassafety.ewt.url}")
    public String targetUrl;

    @Override
    public List<PlatformCompanyManageResp> companyManage(ScreenCompanyManageReq req) {
        List<PlatformCompanyManageResp> respList = new ArrayList<>();
        //查询所有企业
        QueryWrapper<CompanyEntry> getCmJoinWrapper = new QueryWrapper<>();
        getCmJoinWrapper.lambda().eq(CompanyEntry::getIsDeleted, 0);
        List<CompanyEntry> companyEntryList = companyMapper.selectList(getCmJoinWrapper);
        List<String> list1 = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(companyEntryList)) {
            list1 = companyEntryList.stream().map(CompanyEntry::getSpId).collect(Collectors.toList());
        }
        List<String> list2 = new ArrayList<>();
        //查询e网通用户的权限
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        JSONObject availableSps = provider.getAvailableSp(workingUser.getToken());
        if (ObjectUtils.isEmpty(availableSps)) {
            return respList;
        }
        availableSps.getJSONArray("items").forEach(sp -> {
            JSONObject spObj = JSONUtil.parseObj(sp);
            list2.add(spObj.getStr("id"));
        });
        List<String> spIds = list1.stream()
                .filter(list2::contains)
                .collect(Collectors.toList());
        String body = provider.queryCompany(spIds, req.getSpName(), req.getScale(), targetUrl);
        List<QueryCompanyResp> companyResps = JSONArray.parseArray(body, QueryCompanyResp.class);
        //查询企业下的设备
        QueryWrapper<Dtu> queryDtuWrapper = new QueryWrapper<>();
        queryDtuWrapper.lambda().eq(Dtu::getIsDeleted, 0).in(Dtu::getSpId, spIds);
        List<Dtu> dtuList = dtuMapper.selectList(queryDtuWrapper);
        //根据企业进行分组算设备数量合安装数量
        Map<String, List<Dtu>> dtuMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(dtuList)) {
            dtuMap = dtuList.stream().collect(Collectors.groupingBy(Dtu::getSpId));
        }
        if (CollectionUtils.isNotEmpty(companyResps)) {
            for (QueryCompanyResp companyResp : companyResps) {
                PlatformCompanyManageResp resp = new PlatformCompanyManageResp();
                resp.setSpId(companyResp.getSpId());
                resp.setPId(companyResp.getPId());
                resp.setSpName(companyResp.getSpName());
                resp.setScale(companyResp.getScale());
                resp.setScaleStr(companyResp.getScaleStr());
                resp.setSpShortName(companyResp.getSpShortName());
                resp.setCreateTime(companyResp.getCreateTime());
                if (dtuMap.containsKey(companyResp.getSpId())) {
                    List<Dtu> dtus = dtuMap.get(companyResp.getSpId());
                    resp.setImeiSum(dtus.size());
                    //过滤掉没绑定客户的属于安装了设备
                    List<Dtu> appPushs = dtus.stream().filter(dtu -> {
                        return dtu.getConsumerId() > 0;
                    }).collect(Collectors.toList());
                    resp.setInstallSum(appPushs.size());
                }
                respList.add(resp);
            }
        }

        //根据条件查询e网通企业管理接口
        return respList;
    }
}
